<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
      <el-table :data="rolesList" border stripe>
        <!-- 展开 -->
        <el-table-column label="展开" type="expand" width="50px">
          <template v-slot="{row}">
            <el-row v-for="item1 in row.children" :key="item1.id" :class="['bdbottom']">
              <el-col :span="4">
                <!-- 一级权限 -->
                <el-tag type="danger" @close="removethree(row,item1.id)" closable>
                  {{item1.authName}}</el-tag><i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <el-row v-for="item2 in item1.children" :key="item2.id">
                  <el-col :span="4">
                    <!-- 二级权限 -->
                    <el-tag type="warning" @close="removethree(row,item2.id) " closable>
                      {{item2.authName}}</el-tag><i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="20">
                    <!-- 三级权限 -->
                    <el-tag v-for="item3 in item2.children" :key="item3.id" closable @close="removethree(row,item3.id)">
                      {{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(row)">编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="remove(row.id)">删除
            </el-button>
            <el-tooltip content="权限分配" placement="top" :enterable=false>
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRoleDialogVisible(row)">分配权限
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rolesDialogVisible" width="30%" @close="closeRuleDialog">
      <!-- 主体 -->
      <el-tree :default-checked-keys="checkedList" :data="rightsList" :props="{label:'authName'}" show-checkbox
        node-key="id" default-expand-all ref="mytree">
      </el-tree>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="rolesDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveRights">确认
        </el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="resetaddForm">
      <!-- 主体区域 -->
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddForm">确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="reseteditForm">
      <!-- 主体区域 -->
      <el-form ref="editForm" :model="editForm" label-width="80px" :rules="addFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>

      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      rolesDialogVisible: false,
      // 树状权限列表
      rightsList: [],
      // 选中的权限
      checkedList: [],
      // 分配权限ID
      rowId: 0,
      // 添加角色对话框显隐
      addDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '角色名称', trigger: 'blur' }
        ]
      },
      // 编辑角色
      editDialogVisible: false,
      editForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 渲染角色权限列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      this.rolesList = res.data
    },
    // 删除权限
    removethree (row, id) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
        row.children = res.data
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 分配权限弹出
    async showRoleDialogVisible (row) {
      this.rowId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.rightsList = res.data
      this.getCheckedList(row, this.checkedList)
      // console.log(this.checkedList)
      this.rolesDialogVisible = true
    },
    // 提取选中三级权限放到数组中
    getCheckedList (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getCheckedList(item, arr)
      })
    },
    // 确认分配权限
    async saveRights () {
      const arr = [...this.$refs.mytree.getHalfCheckedKeys(), ...this.$refs.mytree.getCheckedKeys()]
      const str = arr.join(',')
      // console.log(str)
      const { data: res } = await this.$http.post(`roles/${this.rowId}/rights`, { rids: str })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.rolesDialogVisible = false
    },
    // 关闭对话框清空表单
    closeRuleDialog () {
      this.checkedList = []
    },

    //
    //
    // 添加请求点击提交
    saveAddForm () {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    // 添加对话框关闭
    resetaddForm () {
      this.$refs.addForm.resetFields()
      // console.log(this.$refs.addForm)
    },
    // 编辑对话框弹出
    showEditDialog (row) {
      this.editDialogVisible = true
      // console.log(row)
      // const { data: res } = await this.$http.get(`roles/${row.id}`)
      // if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      // this.editForm = res.data
      this.editForm = { ...row }
      // console.log(this.editForm)
    },
    // 编辑对话框关闭
    reseteditForm () {
      this.$refs.editForm.resetFields()
    },
    // 编辑点击提交
    saveEditForm () {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(`roles/${this.editForm.id}`,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    // 删除
    remove (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRolesList()
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }

}

</script>

<style scoped lang='less'>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-top: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
